<?php  
namespace Auth;

use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\Key;

require 'vendor/autoload.php';

class JwtToken {
    private $secretKey;  
    private $algorithm = 'HS256';  

    public function __construct() {
        $this->secretKey = 'key666'; // 从环境变量获取密钥
    }

    public function generateJwt($user) {
        $md5User = md5($user);
        $hashUser = hash('sha256', $user);

        $payload = [
            'user' => $user,
            'md5User' => $md5User,
            'hashUser' => $hashUser,
            'iat' => time(), // issued at
            'exp' => time() + 3600 // expires in 1 hour
        ];  

        return JWT::encode($payload, $this->secretKey, $this->algorithm, 'ojbk');  
    }

    public function validateJwt($jwt) {
        try {
            $key = new Key($this->secretKey, $this->algorithm);
            $decoded = JWT::decode($jwt, $key);
            return $decoded; // 返回解码后的数据
        } catch (ExpiredException $e) {
            error_log('Token expired: ' . $e->getMessage());
            return false; // Token expired
        } catch (SignatureInvalidException $e) {
            error_log('Invalid signature: ' . $e->getMessage());
            return false; // Invalid signature
        } catch (BeforeValidException $e) {
            error_log('Token not valid yet: ' . $e->getMessage());
            return false; // Token not valid yet
        } catch (Exception $e) {
            error_log('JWT error: ' . $e->getMessage());
            return false; // Other exceptions
        }
    }   
}
